package hong.jun.Filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.IZuulFilter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
@Component
public class LoginFilter  extends ZuulFilter {
    private static final Logger log = LoggerFactory.getLogger(LoginFilter.class);
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;//过滤器类型
    }

    @Override
    public int filterOrder() {
        return 0;//执行级别
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String url = request.getRequestURI();
        log.info("请求地址："+url);
        //2.判断是否包含在： static/**  ，/login , /register
        if(url.endsWith("/login ") || url.endsWith("/register ") || url.contains("/static/") ){
            return false;
        }
        return true;
    }


    @Override
    public Object run() throws ZuulException {//处理
        RequestContext currentContext = RequestContext.getCurrentContext();//请求的上下文路径
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        String token = request.getParameter("T-TOKEN");
        response.setCharacterEncoding("utf-8");//设置编码
        response.setContentType("application/json;charset=utf-8");
        if (StringUtils.isBlank(token)){
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("sccess","false");
            hashMap.put("message","没有登录");
            String jsonString = JSON.toJSONString(hashMap);
            try {
                response.getWriter().print(jsonString);//返回客户端
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//设置401返回状态
            } catch (IOException e) {
                e.printStackTrace();
            }
            currentContext.setSendZuulResponse(false);//阻止向后执行
        }
        return null;//无意义 占位
    }
}
